<template>
  <div>
    <el-card class="!border-none mb-4" shadow="never">
      <el-form class="mb-[-16px]" :model="queryParams" inline>

        <el-form-item label="院区/楼栋">
          <el-cascader :options="searchLists.cb_lists" clearable v-model="queryParams.cb_ids" filterable
                       :props="props1"/>
        </el-form-item>

        <el-form-item label="房间名" prop="room_keyword">
          <el-input class="w-[280px]" v-model="queryParams.room_keyword" clearable placeholder="请输入房间名"/>
        </el-form-item>

        <el-form-item label="设备信息" prop="device_keyword">
          <el-input class="w-[280px]" v-model="queryParams.device_keyword" clearable
                    placeholder="请输入设备名称/编号"/>
        </el-form-item>

        <el-form-item label="记录时间" prop="log_time">
          <daterange-picker v-model:startTime="queryParams.start_time"
                            v-model:endTime="queryParams.end_time"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" v-loading="pager.loading" shadow="never">
      <!--      <el-button v-perms="['room.room_apartment_device/add']" type="primary" @click="handleAdd">-->
      <!--        <template #icon>-->
      <!--          <icon name="el-icon-Plus"/>-->
      <!--        </template>-->
      <!--        新增-->
      <!--      </el-button>-->
      <el-button type="primary" :disabled="!selectData.length" @click="handleCopyS(selectData)">
        <template #icon>
          <icon name="el-icon-Plus"/>
        </template>
        新增水表
      </el-button>
      <el-button type="primary" :disabled="!selectData.length" @click="handleCopyD(selectData)">
        <template #icon>
          <icon name="el-icon-Plus"/>
        </template>
        新增电表
      </el-button>
      <el-button
          v-perms="['room.room_apartment_device/delete']"
          :disabled="!selectData.length"
          @click="handleDelete(selectData)">
        删除
      </el-button>

      <el-button type="warning" @click="monthInit">
        <template #icon>
          <icon name="el-icon-Plus"/>
        </template>
        月初始化
      </el-button>

      <div class="mt-4">
        <el-table :data="pager.lists" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="序号" prop="sort" width="80" show-overflow-tooltip/>

          <el-table-column label="房间" prop="room">
            <template #default="{ row }">
              <view v-if="row.room">
                <view v-if="row.campus">{{ row.campus.name }} <br/></view>
                <view v-if="row.room.building">{{ row.room.building.name }} <br/></view>
                {{ row.room.name }}
              </view>
            </template>
          </el-table-column>

          <el-table-column label="住户" prop="user" width="150">
            <template #default="{ row }">
              <view v-for="(user_info, user_index) in row.room.user" :key="user_index">
                {{ user_info.user_name }} / {{ user_info.user_mobile }} <br/>
              </view>
            </template>
          </el-table-column>

          <el-table-column label="设备" prop="device_name">
            <template #default="{ row }">
              {{ row.device_name }} <br/>
              {{ row.device_no }} <br/>
              {{ row.device_type_text }}
            </template>
          </el-table-column>

          <el-table-column label="底数">
            <template #default="scope">
              <!--@change="setSave(scope.row,scope.$index,'base_number')"-->
              <el-input v-model="scope.row.base_number"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row,scope.$index,'base_number')"
                        @click="clearInput(scope.row, 'base_number')"
                        @blur="setNullInput(scope.row, 'base_number')"
                        @keyup.enter="newEnter(scope.row,scope.$index, 'base_number')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'base_number')"
                        :class="editIndex == 'base_number'+scope.$index ? 'current_color':''"/>
            </template>
          </el-table-column>
          <el-table-column label="读数">
            <!-- 	<template #default="{ row }">
                <el-input v-model="row.reading" @blur="setSave(row,index)"/>
              </template> -->
            <template #default="scope">
              <!--@change="setSave(scope.row,scope.$index,'reading')"-->
              <el-input v-model="scope.row.reading"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row, scope.$index,'reading')"
                        @click="clearInput(scope.row, 'reading')"
                        @blur="setNullInput(scope.row, 'reading')"
                        @keyup.enter="newEnter(scope.row, scope.$index, 'reading')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'reading')"
                        :class="editIndex == 'reading'+scope.$index ? 'current_color' : ''"/>
            </template>
          </el-table-column>

          <el-table-column label="使用量" prop="use_total" show-overflow-tooltip/>

          <el-table-column label="设备系数">
            <template #default="scope">
              <el-input v-model="scope.row.coefficient"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row,scope.$index,'coefficient')"
                        @click="clearInput(scope.row, 'coefficient')"
                        @blur="setNullInput(scope.row, 'coefficient')"
                        @keyup.enter="newEnter(scope.row,scope.$index, 'coefficient')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'coefficient')"
                        :class="editIndex == 'coefficient'+scope.$index ? 'current_color':''"/>
            </template>
          </el-table-column>
          <el-table-column label="水电价">
            <template #default="scope">
              <el-input v-model="scope.row.price"
                        :placeholder="scope.row.get_enter"
                        @focus="changeColor(scope.row,scope.$index,'price')"
                        @click="clearInput(scope.row, 'price')"
                        @blur="setNullInput(scope.row, 'price')"
                        @keyup.enter="newEnter(scope.row,scope.$index, 'price')"
                        :ref="(el:refItem) => handleSetInputMap(el, scope.$index,'price')"
                        :class="editIndex == 'price'+scope.$index ? 'current_color':''"/>
            </template>
          </el-table-column>

          <el-table-column label="总费用" prop="total_fee" show-overflow-tooltip/>

          <!--<el-table-column label="电梯费" prop="lift_fee" show-overflow-tooltip />-->
          <!--<el-table-column label="二次压力费" prop="second_pressure_fee" show-overflow-tooltip />-->
          <el-table-column label="记录时间" prop="log_time" show-overflow-tooltip/>

          <!--                  <el-table-column label="读数" prop="reading">-->
          <!--                    <template #default="{ row }">-->
          <!--                      <el-input v-model="row.reading" placeholder="请输入读数" @input="setSave(row)" />-->
          <!--                    </template>-->
          <!--                  </el-table-column>-->
          <!--                  <el-table-column label="底数" prop="base_number">-->
          <!--                    <template #default="{ row }">-->
          <!--                      <el-input v-model="row.base_number" placeholder="请输入底数" @input="setSave(row)" />-->
          <!--                    </template>-->
          <!--                  </el-table-column>-->
          <!--                  <el-table-column label="使用量" prop="use_total" show-overflow-tooltip />-->
          <!--                  <el-table-column label="设备系数" prop="coefficient" show-overflow-tooltip />-->
          <!--                  <el-table-column label="水电价" prop="price" show-overflow-tooltip />-->
          <!--                  <el-table-column label="总费用" prop="total_fee" show-overflow-tooltip />-->
          <!--                  <el-table-column label="记录时间" prop="log_time" show-overflow-tooltip />-->

          <!--          <el-table-column label="状态" prop="status" width="60">-->
          <!--            <template #default="{ row }">-->
          <!--              <dict-value :options="dictData.show_status" :value="row.status"/>-->
          <!--            </template>-->
          <!--          </el-table-column>-->

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button v-if="row.room_master != 1" type="danger" size="small" @click="handleDelete(row.id)">
                删除
              </el-button>
              <el-button v-if="row.room_master == 1" type="warning" size="small" @click="handleCopyS(row.id)">
                新增水表
              </el-button>
              <el-button v-if="row.room_master == 1" type="warning" size="small" @click="handleCopyD(row.id)">
                新增电表
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex mt-4 justify-end">
        <pagination v-model="pager" @change="getLists"/>
      </div>
    </el-card>
    <edit-popup v-if="showEdit" ref="editRef" :dict-data="dictData" @success="getLists" @close="showEdit = false"/>
  </div>
</template>

<script lang="ts" setup name="roomApartmentDeviceLists">
import {usePaging} from '@/hooks/usePaging'
import {useDictData} from '@/hooks/useDictOptions'
import {
  apiRoomApartmentDeviceLists,
  apiRoomApartmentDeviceDelete,
  apiRoomApartmentDeviceSave, apiRoomApartmentDeviceCopy
} from '@/api/room/room_apartment_device'
import {timeFormat} from '@/utils/util'
import feedback from '@/utils/feedback'
import EditPopup from './edit.vue'
import {reactive} from "vue";
import {apartmentSearchLists, apiRoomApartmentNewMonth} from "@/api/room/room_apartment";

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
// 是否显示编辑框
const showEdit = ref(false)

type refItem = Element | null
const editIndex = ref('')
const inputRefMap = ref({})
const props1 = {
  checkStrictly: true
}

// 查询条件
const queryParams = reactive({
  cid: '',
  rid: '',
  add_time: '',
  status: '',
  device_id: '',
  coefficient: '',
  price: '',
  base_number: '',
  reading: '',
  use_total: '',
  // lift_fee: '',
  // second_pressure_fee: '',
  total_fee: '',
  log_time: '',
  start_time: '',
  end_time: '',
  bid: '',
  cb_ids: '',
  room_keyword: '',
  device_keyword: ''
})

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
  selectData.value = val.map(({id}) => id)
}

// 获取字典数据
const {dictData} = useDictData('show_status')

const searchLists = reactive({
  cb_lists: [],
})
const getSearchLists = async () => {
  const lists = await apartmentSearchLists([])
  searchLists.cb_lists = lists.cb_lists
  return lists;
}
getSearchLists()

// 分页相关
const {pager, getLists, resetParams, resetPage} = usePaging({
  fetchFun: apiRoomApartmentDeviceLists,
  params: queryParams
})

// 添加
const handleAdd = async () => {
  showEdit.value = true
  await nextTick()
  editRef.value?.open('add')
}

// 编辑
const handleEdit = async (data: any) => {
  showEdit.value = true
  await nextTick()
  editRef.value?.open('edit')
  editRef.value?.setFormData(data)
}

const setSave = async (data: any) => {
  await apiRoomApartmentDeviceSave(data);
}
const changeColor = async (data: any, index: any, name: any) => {
  editIndex.value = name + index
}
const newEnter = async (data: any, index: any, name: any) => {
  const val = data[name]
  if (val && val * 1 != data['get_enter'] * 1) {
    setSave(data)
  }
  if (val == '') {
    setNullInput(data, name)
  }

  const num = parseInt(index) + 1
  editIndex.value = num
  const item = name + num
  inputRefMap.value[`Input_Ref_${item}`].input.focus();

  clearInput(pager.lists[num], name);
}
const clearInput = async (row: any, key: any,) => {
  const val = row[key]
  if (val) {
    row.get_enter = val
  }
  row[key] = ''
}
const setNullInput = async (row: any, key: any,) => {
  if (row[key] == '') {
    row[key] = row.get_enter
  }
  if (row[key] != '' && row[key] * 1 != row.get_enter * 1) {
    setSave(row)
  }
}
/** 动态设置Input Ref */
const handleSetInputMap = (el: refItem, item: number, name: any) => {
  if (el) {
    const el_name = name + item
    inputRefMap.value[`Input_Ref_${el_name}`] = el;
  }
}

// 删除
const handleDelete = async (id: number | any[]) => {
  await feedback.confirm('确定要删除？')
  await apiRoomApartmentDeviceDelete({id})
  getLists()
}

//复制水表
const handleCopyS = async (id: number | any[]) => {
  await feedback.confirm('确定新增水表？')
  const device_type = 1;
  await apiRoomApartmentDeviceCopy({id, device_type})
  getLists()
}
//复制电表
const handleCopyD = async (id: number | any[]) => {
  await feedback.confirm('确定新增电表？')
  const device_type = 2;
  await apiRoomApartmentDeviceCopy({id, device_type})
  getLists()
}

// 月初始化
const monthInit = async () => {
  await feedback.confirm('确定月初始化？')
  await apiRoomApartmentNewMonth({})
  getLists()
}

// console.error(this.$refs)
getLists()
</script>

<style scoped>
/deep/ .current_color .el-input__wrapper {
  background-color: blanchedalmond !important;
}

.el-button {
  margin-bottom: 10px;
  margin-right: 10px;
  margin-left: 10px;
}
</style>
